package com.threeti.mecool.core.application.acl;

import com.threeti.mecool.core.domain.model.acl.PermissionRoleAchievement;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.domain.model.plan.PlanJobResult;
import com.threeti.mecool.core.infrastructure.persistence.acl.PermissionRoleAchievementRepository;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultSpecs;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PermissionRoleAchievementService {
    @Autowired
    private PermissionRoleAchievementRepository repository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PlanJobResultRepository planJobResultRepository;

    public PermissionRoleAchievement findOne(Long id) {
        return repository.findOne(id);
    }

    public void save(PermissionRoleAchievement target) {
        repository.save(target);
    }

    public Page<PermissionRoleAchievement> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    public List<PermissionRoleAchievement> findByUserLoginName(String userLoginName) {
        User user = userRepository.findByloginName(userLoginName);
        if (user == null) return new ArrayList<PermissionRoleAchievement>(0);
        return repository.findByPermissionRole(user.getPermissionRole());
    }

    public Map<PermissionRoleAchievement, Long> findMonthlyResult(String userLoginName, Date date) {
        List<PermissionRoleAchievement> achievementList = findByUserLoginName(userLoginName);
        Map<PermissionRoleAchievement, Long> ret = new HashMap<PermissionRoleAchievement, Long>(achievementList.size(), 1);
        DateTime dateFrom = new DateTime(date).withDayOfMonth(1);
        DateTime dateTo = dateFrom.plusMonths(1);
        for (PermissionRoleAchievement achievement : achievementList) {
            Specification<PlanJobResult> spec = Specifications.where(PlanJobResultSpecs.finishedJob())
                    .and(PlanJobResultSpecs.finishAtGreaterThanOrEqualTo(dateFrom.toDate()))
                    .and(PlanJobResultSpecs.finishAtLessThat(dateTo.toDate()));
            Long count = planJobResultRepository.count(spec);
            ret.put(achievement, count);
        }
        return ret;
    }
}
